<template>
  <div class="search-component">
    <!-- 显示搜索热词 -->
    
    <!-- 搜索框 -->
    <slot>
      <div class="search-top">
        <van-search
          ref="focusRef"
          v-model="value"
          @search.enter="toSearch"
          shape="round"
          show-action
          :autofocus="true"
          @update:model-value="onSearch"
          @cancel="onCancel"
          @clear='value = ""'
        />
      </div>
    </slot>

    <!-- 搜索框实时关键词 -->
    <div v-show="isHotKeywords" class="search-hot">
        <div @click="toDetail(hotKeywordsInfo.id)" class="hot-read" v-if="hotKeywordsInfo">
          <img :src="hotKeywordsInfo.imgPath" alt="">
          <div class="read-text">
            <div class="text">{{ hotKeywordsInfo.keyword }}</div>
            <div class="read">
              <div class="read1 item">{{ hotKeywordsInfo.category }}</div>
              <div class="item"><van-icon name="search"></van-icon> {{ (hotKeywordsInfo.play/10000).toFixed(2) }}万</div>
              <div class="item"><van-icon name="fire"></van-icon>{{ hotKeywordsInfo.tracks }}集</div>
            </div>
          </div>
          <van-icon name="play-circle-o" size="26" color="#999"/>
        </div>
        <div class="hot-item"
          v-for="(item,index) in hotKeywordsList"
          :key="index"
          @click="clickToSearch(item.keyword)"
        > {{ item.keyword }}</div>
    </div>
   

    <!-- 显示正常页面 -->
    <div v-show="!isHotKeywords">
      <!-- 历史记录 -->
      <div v-if="historyList.length>0" class="search-history">
        <div class="history-title">
          <div>搜索历史</div>
          <van-icon @click="clearHistory" name="delete" color="#999"></van-icon>
        </div>

        <div class="history-content">
          <div class="item" 
            v-for="(item,index) in historyList" 
            :key="index"
            @click="clickToSearch(item)"
          >{{ item }}</div>
        </div>
      </div>

      <!-- 标题滑动栏 -->
      <TopTitleList :currentIndex="currentIndex" :chartsTitleList="chartsTitleList" @onClickTitle1="onClickTitle"></TopTitleList>

      <!-- 标题列表 -->
      <div class="search-keyword">

        <div class="keyword-item"
          v-for="(item,index) in searchKeywordsList"
          :key="index"
          @click=clickToSearch(item.word)
        >
          <div :class="['item-num', index==0?'red':index==1?'orange':index==2?'yellow':'']">{{ index+1 }}</div>
          <div class="item-text-icon">
            <div class="item-text">{{ item.word }}</div>
            <van-icon v-show="item.shift==1" name="back-top" color="red"></van-icon>
            <van-icon v-show="item.shift==-1" name="down" color="green"/>
            <van-icon v-show="item.shift==0" name="minus" color="#999"/>
          </div>
        </div>
      
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import TopTitleList from "../TopTitleList/TopTitleList.vue"
import { onMounted } from 'vue';
import searchApi from "../../api/searchApi"
import { DataType } from '../../api/chartsApi';
import { computed } from 'vue';
import {useRouter} from 'vue-router'
import { watch } from 'vue';
import { nextTick } from 'vue';
const router=useRouter();
const emits = defineEmits<{
  (e:'update:modelValue',v:boolean):void,
}>()
const props = defineProps<{
  modelValue:boolean
}>()


const historyList = ref<string[]>([])
const chartsTitleList = ref<DataType[]>([])
const searchKeywordsList = ref<DataType[]>([])
const currentIndex = ref(0);
//回车跳转到search路由
const toSearch=(kw:string)=>{
  if(kw && !historyList.value.some(item=>item==kw)){
    historyList.value.push(kw)
    sessionStorage.setItem('history_list',JSON.stringify(historyList.value))
  }
   router.push({
    name:'search',
    params:{
       kw
    }
   })
};

/* 点击 跳转搜索详情页 */
const clickToSearch = (key:string)=>{
  if(!historyList.value.some(item=>item==key)){
    historyList.value.push(key)
    sessionStorage.setItem('history_list',JSON.stringify(historyList.value))
  }
  router.push({
    name:'search',
    params:{
      kw:key
    }
   })
  
}

/* 点击热词第一个，跳转商品详情页 */
const toDetail = (id:number)=>{
  router.push({
    name:'detail',
    params:{
      id,
    }
   })
}


/* 搜集搜索内容数据 */
const value = ref('')
/* 热词数据 */
const hotKeywordsList = ref<DataType[]>([])
const hotKeywordsInfo = ref<DataType>()
let timer:any;

/* 搜索内容事件 */
const onSearch = (val:string)=>{
  value.value = val.trim()
  timer && clearTimeout(timer)

  timer = setTimeout(()=>{
    getHotKeywordsList(value.value)
  },200)
}

const isHotKeywords = computed(()=>{
  return hotKeywordsList.value.length?true:false;
})




/* 点击取消 */
const onCancel = ()=>{
  emits('update:modelValue',false)
  value.value = '';
}

const focusRef = ref();
watch(()=>props.modelValue,()=>{
  nextTick(()=>{
    focusRef.value?.focus();
  })
},{deep:true,immediate:true});

/* 点击标题的事件 */
const onClickTitle = (index:number,id?:number)=>{
  currentIndex.value = index;
  getSearchKeywordsList(id!)
  
}


/* 清空历史机记录 */
const clearHistory = ()=>{
  historyList.value = [];
  sessionStorage.removeItem('history_list')
}



/* 生命周期 */
onMounted(()=>{
  
  getSearchTitleList()
  /* 历史记录查询 */
  historyList.value = JSON.parse(sessionStorage.getItem('history_list')!) ||[]
})

/* 获取搜索页标题列表的功能函数 */
const getSearchTitleList = async ()=>{
  try {
    let res = await searchApi.getSearchTitleList()
    chartsTitleList.value = res.category;
    getSearchKeywordsList(res.category[0]?.categoryId)
  } catch (error) {
    console.log(error);
    
  }
}

/* 获取关键字列表的功能函数 */
const getSearchKeywordsList = async (id:number)=>{
  try {
    let res = await searchApi.getSearchKeywordsList(id)
    searchKeywordsList.value = res.hotWordResultList;
  } catch (error) {
    console.log(error);
    
  }
}

/* 获取实时搜索热词列表 */
const getHotKeywordsList = async (kw:string)=>{
  try {
    let res = await searchApi.getHotKeywordsList(kw)
    if(res.ret == 200) {
      hotKeywordsList.value = res.data.result.queryResultList;
      hotKeywordsInfo.value = res.data.result.albumResultList[0]
    }
  } catch (error) {
    console.log(error);
    
  }
}


</script>

<style  lang="less" scoped>
:deep(.van-search__action){
  font-size: 16px;
}

/* 实时搜索热词 */
.search-hot{
  font-size: 16px;
  padding: 0 10px;
  .hot-read{
    border-bottom: 1px #ccc solid;
    padding: 10px 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    img{
      width: 40px;
      height: 40px;
      border-radius: 5px;
    }
    .read-text{
      width: 270px;
      height: 36px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .text{
        font-size: 14px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .read{
        display: flex;
        align-items: center;
        font-size: 13px;
        color: #999;
        .read1{
          border: .5px solid #999;
          border-radius: 3px;
          padding: 1px 3px 0;
          font-size: 12px;
        }
        .item{
          margin-right: 10px;
        }
      }
    }
  }
  .hot-item{
    border-bottom: 1px #ccc solid;
    padding: 10px 0;
    font-size: 15px;
    color: #555;
  }

}

/* 历史记录 */
.search-history{
  padding: 10px 20px;
  font-size: 20px;
  .history-title{
    display: flex;
    justify-content: space-between;
  }
  .history-content{
    display: flex;
    flex-wrap: wrap;
    margin-top: 10px;
    .item{
      background-color: #eee;
      padding: 10px;
      margin-right: 5px;
      margin-bottom: 5px;
      border-radius: 5px;
      font-size: 16px;
    }
  }
}

/* 关键字列表 */
.search-keyword{
  padding: 10px 20px;
  border-top: 1px solid #eee;
  .keyword-item{
    display: flex;
    padding-top: 10px;
    .item-num{
      flex-shrink: 0;
      line-height: 40px;
      text-align: center;
      height: 40px;
      width: 20px;
      margin-right: 20px;
      font-size: 24px;
      color: #dabda6;
      &.red{
        color:red;
        font-size: 26px;
      }
      &.orange{
        color:orange;
        font-size: 26px;
      }
      &.yellow{
        color:yellow;
        font-size: 26px;
      }
    }
    .item-text-icon{
      flex-grow: 1;
      display: flex;
      font-size: 20px;
      justify-content: space-between;
      padding: 10px 0 20px;
      border-bottom: 1px #eee solid;
      
    }
  }
}

</style>